import React from 'react';
import { Row, Col, Form, Input, Button, Spin, DatePicker, Table, Select, Popconfirm, Card, message, Upload, Icon } from 'antd';
import moment from 'moment';
import { getJsonReactNode } from '../../utils';
import { DEFAULT_PAGE_SIZE } from '../../utils/constants';
import styles from '../common_left.css';
import CaseModal from './CaseModal';


const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

@Form.create()
class CaseTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = { // 状态树，存储各个控件的状态值，供外部调用
      currentRecord: {}, // 定义当前行变量，通过判断变量是否有值来决定走新增 or 修改
      modalVisible: false, // 定义是否显示新增/编辑弹窗页面
    };
  }
  handleSearch = () => { // 查询方法
    const {  // 该组件的属性，由外部传入参数
      dispatch,
      form: { validateFields, getFieldsValue },
    } = this.props;
    validateFields((errors) => {
      if (errors) {
        return;
      }
      const data = {
        ...getFieldsValue(),
      };
      dispatch({ // 调用接口，请求数据
        type: 'casemanage/fetchCase', //  models的namespace + effects的方法名，也可以是reducers的方法
        payload: {
          params: data,
        },
      });
    });
  };
  handleUpdateCaseDetail = (record) => {
    this.setState({ // 设置状态树
      currentRecord: record,  // 设置状态树中当前行对象为空，这样可通过判断对象是否为空，来决定走编辑or新增
      modalVisible: true, // 设置新增/编辑表单可见
    });
  };
  handledeleteCase = (record) => {
    this.props.dispatch({  // 调用更新接口
      type: 'casemanage/deleteCase',
      payload: {
        recordParams: record,
      },
    });
  };
  handleUpdateCase = (field, value, record) => {
    const { dispatch, form: { setFieldsValue } } = this.props;
    const realField = field.slice(0, (0 - `$${record.id}`.length)); // .slice 截取字符串，获取真实的field名称，此处避免更新一个字段将整列都更新了
    let toapivalue = '';
    if (realField === 'devtest_endtime') {
      toapivalue = value ? moment(value).format('YYYY-MM-DD') : '';
    } else if (realField === 'dev_status' || 'test_status') {
      toapivalue = value || 'undo';
    } else if (realField === 'comment') {
      toapivalue = value || '';
    } else {
      toapivalue = '';
    }
    const nextRecord = { ...record };
    nextRecord[realField] = toapivalue;
    dispatch({
      type: 'casemanage/updateCase',
      payload: {
        updateparam: nextRecord,
        reset: () => {
          const changeObj = {};
          changeObj[field] = record[realField]; // 回调方法,若修改接口调用失败,则将值还原
          setTimeout(() => { // 确保排在form的默认设置逻辑之后。。
            setFieldsValue(changeObj);
          }, 10);
        },
      },
    });
  };
  // 下载用例模板
  handleDownloadAtta = () => {
    const { form: { getFieldsValue } } = this.props;
    const data = {
      ...getFieldsValue(),
    };
    window.location.href = 'api/downloadCase/';
  };
  // 下载用例内容
  handleDownloadContent = () => {
    const { form: { getFieldsValue } } = this.props;
    const data = {
      ...getFieldsValue(),
    };
    const project_name=data['project_name'];
    const rt_version=data['rt_version'];
    window.location.href = `api/downloadCaseContent/?rt_version=${rt_version}&project_name=${project_name}`;
  };

  handleupload = () => {
    const {  // 该组件的属性，由外部传入参数
      dispatch,
      form: { validateFields, getFieldsValue },
    } = this.props;
    const data = {
      ...getFieldsValue(),
    };
    const project_name=data['project_name'];
    const rt_version=data['rt_version'];
    const sheetname=data['sheetname'];
    const UploadProps = {
      name: 'casefile',
      action: `/api/uploadCase/?project_name=${project_name}&rt_version=${rt_version}&sheetname=${sheetname}`,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: (info) => {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.status === 10025) {
            message.warning('项目名或版本号为空或case为空');
          } else if (info.file.response.status === 200) {
            message.success(`${info.file.name} file uploaded successfully`);
          } else {
            message.error('上传失败');
          }
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };
    return UploadProps;
  };
  handleSendSmokeResult = () => {
    const { dispatch, form: { getFieldsValue } } = this.props;
    const data = {
      ...getFieldsValue(),
    };
    const project_name = data['project_name'];
    const rt_version = data['rt_version'];
    const sendparam = {
      'project_name': project_name,
      'rt_version': rt_version,
    };
    if (project_name && rt_version) {
      dispatch({
        type: 'casemanage/sendSmokeReport',
        payload: {
          reportparam: sendparam,
        },
      });
    } else {
      message.warning('项目名或版本号为空,不可发送');
    }
  };
  // 将获取到的接口数据进行渲染
  render() {
    const { dispatch, loading, caseinfo, projectlist, form: { getFieldDecorator } } = this.props;
    const status = [
      {
        key: 'pass',
        name: '通过',
      },
      {
        key: 'fail',
        name: '失败',
      },
      {
        key: 'undo',
        name: '未执行',
      },
      {
        key: 'block',
        name: '阻塞',
      },
      {
        key: 'cancel',
        name: '取消',
      },
    ];
    // 定义表头字段及取值内容
    const columns = [
      {
        title: '模块',
        dataIndex: 'module',
        key: 'module',
      },
      {
        title: '用例名称',
        dataIndex: 'case_name',
        key: 'case_name',
      },
      {
        title: '测试步骤',
        dataIndex: 'case_step',
        key: 'case_step',
      },
      {
        title: '开发负责人',
        dataIndex: 'assigne',
        key: 'assigne',
      },
      {
        title: '版本号',
        dataIndex: 'rt_version',
        key: 'rt_version',
      },
      {
        title: 'DEV验证结果',
        dataIndex: 'dev_status',
        key: 'dev_status',
        render: (text, record) => {
          const field = `dev_status$${record.id}`;
          // const nowDate = new Date().valueOf();// 当前时间转换成时间戳
          // const editable = record.devtest_endtime ? ((new Date(moment(record.devtest_endtime).format('YYYY-MM-DD')).valueOf()) > nowDate) : false;
          return getFieldDecorator(field, {
            initialValue: text,
          })(
            <Select
              style={{ width: '100%' }}
              size="small"
              showSearch
              optionFilterProp="children"
              // disabled={editable}
              onChange={(value) => {
                if (value !== text) {
                  this.handleUpdateCase(field, value, record);
                }
              }}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {
                status.map((item, index) => {
                  return <Option key={index} value={item.key}>{item.name}</Option>;
                })
              }
            </Select>
          );
        },
      },
      {
        title: 'QA验证结果',
        dataIndex: 'test_status',
        key: 'test_status',
        render: (text, record) => {
          const field = `test_status$${record.id}`;
          return getFieldDecorator(field, {
            initialValue: text,
          })(
            <Select
              style={{ width: '100%' }}
              size="small"
              showSearch
              optionFilterProp="children"
              onChange={(value) => {
                if (value !== text) {
                  this.handleUpdateCase(field, value, record);
                }
              }}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {
                status.map((item, index) => {
                  return <Option key={index} value={item.key}>{item.name}</Option>;
                })
              }
            </Select>
          );
        },
      },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <div className={styles.operation}>
              <a onClick={() => this.handleUpdateCaseDetail(record)}>
                修改
              </a>
              <Popconfirm title={'确定删除？'} onConfirm={() => this.handledeleteCase(record)}>
                <a>删除</a>
              </Popconfirm>
            </div>
          );
        },
      },
      // {
      //   title: '备注',
      //   dataIndex: 'comment',
      //   key: 'comment',
      //   render: (text, record) => {
      //     const field = `comment$${record.id}`;
      //     return getFieldDecorator(field, {
      //       initialValue: text,
      //     })(
      //       <Input
      //         style={{ width: '100%' }}
      //         size="small"
      //         onBlur={(e) => {
      //           const value = e.target.value;
      //           if (value !== text) {
      //             this.handleUpdate(field, value, record);
      //           }
      //         }}
      //       />
      //     );
      //   },
      // },
      // {
      //   title: 'dev测试截止时间',
      //   dataIndex: 'devtest_endtime',
      //   key: 'devtest_endtime',
      //   render: (text, record) => {
      //     const field = `devtest_endtime$${record.id}`;
      //     return getFieldDecorator(field, {
      //       // initialValue: moment(text).format('YYYY-MM-DD HH:mm:ss'),
      //       initialValue: text ? moment(text) : null,
      //     })(
      //       <DatePicker
      //         // style={{ width: '100%' }}
      //         size="small"
      //         allowClear={false}
      //         onChange={(value) => {
      //           if (value !== text) {
      //             this.handleUpdateCase(field, value, record);
      //           }
      //         }}
      //       />
      //     );
      //   },
      // },
    ];
    const modalProps = {
      dispatch,
      loading,
      visible: this.state.modalVisible,
      currentUser: this.state.currentRecord,
      onCancel: () => {
        this.setState({
          currentRecord: {},
          modalVisible: false,
        });
      },
    };
    return (
      <div>
        {
          <div>
            <Card style={{ marginBottom: 16 }}>
              <Row gutter={12} style={{ marginBottom: 8 }}>
                <Form>
                  <Col span={6}>
                    <FormItem
                      label="project_name"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('project_name', {
                        initialValue: '',
                      })(
                        <Select
                          showSearch
                          optionFilterProp="children"
                          filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        >
                          <Option key={-1} value="">请选择项目名称</Option>
                          {// 这括号表示括起来的是一个表达式 不同于函数的括号，这里面只能放一个表达式
                            projectlist.map((item, index) => {
                              return (<Option key={index} value={item}>{item}</Option>);
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="版本号"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('rt_version', {
                        initialValue: '',
                      })(
                        < Input />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="模块"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('module', {
                        initialValue: '',
                      })(
                        < Input />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="开发负责人"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('assigne', {
                        initialValue: '',
                      })(
                        < Input />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="sheet名称"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('sheetname', {
                        initialValue: '',
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="开发测试结果"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('dev_status', {
                        initialValue: '',
                      })(
                        <Select>
                          <Select.Option key={-1} value="">请选择状态</Select.Option>
                          {
                            status.map((item, index) => {
                              return (
                                <Select.Option key={index} value={item.key}>{item.name}</Select.Option>
                              );
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="QA测试结果"
                      {...formItemLayout}
                    >
                      {getFieldDecorator('test_status', {
                        initialValue: '',
                      })(
                        <Select>
                          <Select.Option key={-1} value="">请选择状态</Select.Option>
                          {
                            status.map((item, index) => {
                              return (
                                <Select.Option key={index} value={item.key}>{item.name}</Select.Option>
                              );
                            })
                          }
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Form>
              </Row>
              <Row gutter={12} style={{ marginBottom: 8 }}>
                <div className={styles.btnGroup}>
                  <Button type="primary" loading={loading} onClick={this.handleSearch}>查询</Button>
                  <Button type="primary" icon="download" onClick={this.handleDownloadAtta}>下载模板</Button>
                  <Button type="primary" onClick={this.handleSendSmokeResult}>发送测试结果</Button>
                  <Button type="primary" icon="download" onClick={this.handleDownloadContent}>下载用例内容</Button>
                  <Upload {...this.handleupload()} >
                    <Button>
                      <Icon type="upload" /> 上传用例
                    </Button>
                    <span
                      style={{
                        marginLeft: 16,
                        color: '#cccccc',
                      }}
                    >
                          仅支持.xls格式文件
                        </span>
                  </Upload>
                </div>
              </Row>
            </Card>
            <Table
              columns={columns}
              dataSource={caseinfo}
              loading={loading}
              rowKey={record => record.id}
              pagination={{
                pageSize: DEFAULT_PAGE_SIZE,
              }}
              bordered
            />
            <CaseModal {...modalProps} />
          </div>
        }
      </div>
    );
  }
}

export default CaseTable;
